package com.pig4cloud.pigx.auth.service;

import cn.hutool.core.util.StrUtil;
import com.pig4cloud.pigx.common.security.component.SpringContextHolder;
import com.pig4cloud.pigx.common.security.util.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.event.LogoutSuccessEvent;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Service;

/**
 * @description:
 * @Author 兔子不吃窝边曹
 * @create 2022/8/5 14:44
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class PigxTokenDealServiceImpl {

    private final TokenStore tokenStore;

    /**
     * 删除 请求令牌 和 刷新令牌
     *
     * @param token 请求令牌
     * @return R
     */
    public R<Boolean> removeToken(String token) {

        OAuth2AccessToken accessToken = tokenStore.readAccessToken(token);
        if (accessToken == null || StrUtil.isBlank(accessToken.getValue())) {
            return R.ok(Boolean.TRUE, "退出失败，token 无效");
        }

        OAuth2Authentication auth2Authentication = tokenStore.readAuthentication(accessToken);

        // 清空redis用户缓存信息

        // 清空access token
        tokenStore.removeAccessToken(accessToken);

        // 清空 refresh token
        OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
        tokenStore.removeRefreshToken(refreshToken);

        // 发送退出成功事件
        SpringContextHolder.publishEvent(new LogoutSuccessEvent(auth2Authentication));
        return R.ok();
    }
}
